﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Infrastructure.Extension
{
    // Need Microsoft.EntityFrameworkCore

    public static class EFCoreExtension
    {
        /// <summary>
        /// [update part fields,'Id' is required] 
        /// eg: var room = new Blog { Id = 2, Name ="kim",Title="title"}; dbContext.Update(room, s=>s.Name); Update field name only
        /// </summary>
        public static void Update<T, C>(this C context, T entity, params Expression<Func<T, object>>[] properties) where T : class, new() where C : DbContext
        {
            var dbEntityEntry = context.Entry(entity);
            if (properties != null && properties.Any())
            {
                foreach (var property in properties)
                {
                    dbEntityEntry.Property(property).IsModified = true;
                }
            }
        }

        public static void UpdateRange<T, C>(this C context, IEnumerable<T> entities, bool isNoTracking = true, params Expression<Func<T, object>>[] properties) where T : class, new() where C : DbContext
        {
            foreach (var entity in entities)
            {
                var dbEntityEntry = context.Entry(entity);
                //Notice that:当更新实体指定属性时，若实体从数据库中查询而出，此时实体已被跟踪，则无需处理，若实例化对象而更新对象指定属性，此时需要将其状态修改为Unchanged即需要附加
                if (!isNoTracking) { dbEntityEntry.State = EntityState.Unchanged; }
                if (properties.Any())
                {
                    foreach (var property in properties)
                    {
                        dbEntityEntry.Property(property).IsModified = true;
                    }
                }
            }
        }
    }
}
